
$(function (){
    vm.ticketId =getQueryString("id");
    vm.loadRepairRecordDetail(vm.ticketId)
    for (const argumentsKey in sysEnums.PREVENT_MEASURE_TYPE) {
        vm.measureType.push({
            name:sysEnums.PREVENT_MEASURE_TYPE[argumentsKey],
            value:argumentsKey
        })
    }
    /*获取处理人 要求接口在返回的时候默认第一个人为自己*/
    var url = '../sys/user/loadWorkshopRoleUserList?roleCode=RL13';
    Ajax.request({
        url: url,
        async: true,
        successCallback: function (data) {
            vm.dutyUserIdList = data.userList;
        }
    });
    /*措施优化*/
    if(vm.devMaintenRepair.preventMeasureList.length != 0){
        for(let i = 0;i<=vm.devMaintenRepair.preventMeasureList.length ;i++){
            vm.devMaintenRepair.preventMeasureList[i].isShow = vm.devMaintenRepair.preventMeasureList[i].measureType;
        }
    }

})

var vm = new Vue({
    el: '#rrapp',
    data: {
        showList: true,
        title: null,
        devMaintenRepair: {
            devId: '',
            devCode: '',
            devName: '',
            maintenRecordId: '',
            faultCode: '',
            faultDesc: '',
            faultId: '',
            vrtId: '',
            vfgId: '',
            faultCategoryId: '', // CCC报警分类名称
            faultCategoryName: '', // CCC报警分类名称
            recordDescr: '',
            reason: '',
            solution: '',
            remark: '',
            id: '',
            repairStartDate: '',
            repairEndDate: '',
            big: '',//报警分类大类
            middle: '',//报警分类中
            small: '',//报警分类小类
            preventMeasureList:[],
            attachment:'',
            faultImages:[],
            measureType:'DEV_MAINTENANCE_TICKET',//措施类型
        },
        vfgList: [], // VFG列表
        cccList: [], // CCC列表
        measureType:[],
        categoryCode: '',//业务分类代码，可供设备大类查询
        alarmList: [

        ], //报警代码下拉
        flag: '-1', //是否新增报警代码新增
        faultTree: {},
        desc:'',//现场反馈的值
        devKind:'1',//换件记录选择备件默认的值
        annexListShow:false,//附件列表显示
        annexName:'',//附件名称
        businessId:'',//维修工单id
        isReplaceable:'1',//选择备件进去的
        type:'REPAIR',
        source:'',//用于却别来源
        annexFile:[],
        ticketId:'',
        devCodeAndName:'',//设备名称和name
        dutyUserIdList:[],//处理人员list
        dutyUserIdListNull:[{
            label: '由班组长指定',
            value: 'null'
        }, ],
        ruleValidate:{
            recordDescr: [
                { required: true, message: '请输入故障描述', trigger: 'blur' }
            ],
            reason:[
                { required: true, message: '请输入原因分析', trigger: 'blur' }
            ],
            solution:[
                { required: true, message: '请输入解决办法', trigger: 'blur' }
            ]
        },
        keyModal:false,
        keyPartList:[],//关键零部件
        keyQuarms:{
            repairRecordId:'',//维修记录id
            position:'',//安装位置
            sparePartConsumeRecordId:''//换件记录ID必填
        },
        isSelect:false,
        isList:false,
        loading2:false,
        searchAlarmList:[],//远程搜索值
    },
    computed:{
        /*1、如果是选出来的，那么faultId 这个字段肯定会有值
                2、如果是拍照的，那么faultId 、faultCode、faultDesc都不可能有值
                3、如果是手动录入的，那么faultId 没有值，faultCode和faultDesc有值
              */
        handText:function (){
            if(this.source=='SYSTEM'){
                if(this.devMaintenRepair.faultId){
                    return false
                }else{
                    if(this.desc){
                        return true
                    }else{
                        return  false
                    }
                }
            }else{
                if(this.devMaintenRepair.faultId){
                    return false
                }else{
                    return true
                }
            }
        },
        shotPhotoText:function (){
            if(this.source=='SYSTEM'){
                if(this.devMaintenRepair.faultId){
                    return false
                }else {
                    if(!this.desc){
                        return true
                    }else{
                        return  false
                    }
                }
            }else{
                return false
            }
        },
    },
    methods: {
        /*维修措施*/
        handleTypeChange(i){
            console.log(i,"次数");
            console.log(vm.devMaintenRepair.preventMeasureList[i].measureType,"类型");
            vm.devMaintenRepair.preventMeasureList[i].isShow = vm.devMaintenRepair.preventMeasureList[i].measureType;
            console.log(vm.devMaintenRepair.preventMeasureList[i].isShow,i,"冲锋");
        },
        remoteMethod2:function (query) {
            const that = this;
            if(query.length<3){
                return
            }
            if(query.indexOf('暂无需要报警代码,手动选择录入')>-1){
                vm.flag='0'
                if(vm.devMaintenRepair.faultId){
                    vm.devMaintenRepair.faultId='';
                }
                return;
            }
            var url = '../alarmcodebase/query'+'?devId='+vm.devMaintenRepair.devId+'&alarmCode='+query;
            that.loading2 = true;
            vm.searchAlarmList  =[];
            Ajax.request({
                url: url,
                async: true,
                successCallback: function (r) {
                    that.loading2 = false;
                    let data = r.list;
                    if(r.list.length==0){
                        //暂无需要代码，手动选择
                        that.searchAlarmList.push({
                            value:'000',
                            label:query+'暂无需要报警代码,手动选择录入。'
                        })
                        return
                    }
                    for (let i = 0; i < data.length; i++) {
                        vm.searchAlarmList.push({
                            value:data[i].id,
                            label:data[i].alarmCode+data[i].alarmDesc
                        })
                    }

                }
            });

        },
        /*获取换件记录*/
        getChangeRecord:function () {
            var queryUrl = '../sparepartconsumrecord/list';
            var paramArray = [];
            if (vm.businessId) {
                paramArray.push('businessId=' + vm.businessId);
            }
            paramArray.push('type=' + 'REPAIR');
            if (paramArray.length > 0) {
                queryUrl += '?' + paramArray.join('&');
            }
            $.jgrid && ($.jgrid.info_dialog = function (caption, content, c_b, modalopt) {
                alert(content);
            });
            $("#swapRecord").Grid({
                url: queryUrl,
                height: 110,
                colModel: [
                    {label: '备件编码', name: 'partCode', index: 'PART_CODE', width: 120},
                    {label: '备件名称', name: 'name', index: 'NAME', width: 120},
                    {label: '规格', name: 'spec', index: 'SPEC', width: 120},
                    {label: '添加人', name: 'createUserName', width: 60, sortable: false, hidden: true},
                    {label: '添加时间', name: 'gmtCreate', width: 60, sortable: false, hidden: true},
                    {label: '领料单号', name: 'materCode', width: 60, sortable: false},
                    {label: '使用数量', name: 'num', index: 'NUM', width: 60, editable: true, editrules: {number: true}},
                    {name: 'sparePartId', hidden: true},
                    {name: 'type', hidden: true},
                    {name: 'businessId', hidden: true},
                    {label: 'id', name: 'id', index: 'ID', key: true, hidden: true},
                ],
                forceFit: true,
                cellEdit: true,
                cellsubmit: 'remote',
                cellurl: '../sparepartconsumrecord/update',
                afterSubmitCell(serverresponse, rowid, cellname, value, iRow, iCol) {
                    vm.reload();
                    if (serverresponse.responseJSON.code == 0) {
                        vm.reload();
                        return [true,""];
                    } else {
                        return [false,serverresponse.responseJSON.msg];
                    }
                }
            });
        },
        /*获取附件列表*/
        getAnnexList:function (){
            var queryUrl = '../annexfile/equList';
            var paramArray = [];
            if (vm.businessId) {
                paramArray.push('moduleId=' + vm.businessId);
            }
            paramArray.push('moduleType=' + '1');
            if (paramArray.length > 0) {
                queryUrl += '?' + paramArray.join('&');
            }
            $("#annexList").Grid({
                url: queryUrl,
                height: 150,
                colModel: [
                    {label: '附件标题', name: 'fileName', index: 'FILE_NAME', width: 120},
                    {label: '附件名称', name: 'relName', index: 'REL_NAME', width: 120},
                    {
                        label: '上传时间', name: 'uploadDate', index: 'UPLOAD_DATE', width: 120, formatter: function (value) {
                            return transDate(value, "yyyy-MM-dd hh:mm:ss");
                        }
                    },
                    {label: '上传用户', name: 'createUserName', index: 'CREATE_NAME', width: 60},
                    {
                        label: '操作', width: 60, align: 'center', sortable: false,
                        formatter: function (value, col, row) {
                            return "<div onclick='fileCommonHandle(\"" + row.url + "\", \"" + row.relName + "\")'><i class='fa fa-eye'></i>&nbsp;查看</div>"
                        }
                    },
                    {label: 'id', name: 'id', index: 'ID', key: true, hidden: true}
                ]
            });
        },
        /*附件modal 打开*/
        annexModalShow(){
            vm.annexListShow = true;
            vm.annexFile = {
                id: '',
                moduleType: '1',
                moduleId: vm.businessId,
                relName: '',
                fileName: '',
                url: ''
            };
        },
        /*确认上传*/
        annexSubmit:function (){
            var url = '../annexfile/saveDevEqu';
            Ajax.request({
                url: url,
                params: JSON.stringify(vm.annexFile),
                type: "POST",
                contentType: "application/json",
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.annexListReload()
                        vm.annexListShow = false;
                    });
                }
            });
        },
        /*取消*/
        annexCancel(){
            vm.annexListShow = false;
            vm.annexFile = {
                id: '',
                moduleType: '',
                moduleId: '',
                relName: '',
                fileName: '',
                url: ''
           }
        },
        reload: function (event) {
            vm.showList = true;
            // 清空postData缓存数据
            var postData = $("#swapRecord").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#swapRecord").jqGrid('getGridParam', 'page');
            // 构建查询参数
            var param = {};
            if (vm.businessId) {
                param.businessId = vm.businessId;
            }
            if (vm.type) {
                param.type = vm.type;
            }
            $("#swapRecord").jqGrid('setGridParam', {
                search: true,
                postData: param,
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
        },
        /*附件列表重新加载*/
        annexListReload:function (){
            // 清空postData缓存数据
            var postData = $("#annexList").jqGrid("getGridParam", "postData");
            $.each(postData, function (k, v) {
                delete postData[k];
            });
            var page = $("#annexList").jqGrid('getGridParam', 'page');
            // 构建查询参数
            var param = {};
            if (vm.businessId) {
                param.moduleId = vm.businessId;
            }
            if (vm.type) {
                param.moduleType ='1';
            }
            $("#annexList").jqGrid('setGridParam', {
                search: true,
                postData: param,
                page: page
            }).trigger("reloadGrid", [{page: 1}]);
        },
        /*换件记录删除*/
        del: function (event) {
            let ids = getSelectedRows("#swapRecord");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../sparepartconsumrecord/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        /*附件删除*/
        delAnnexList:function (){
            var ids = getSelectedRows("#annexList");
            if (ids == null) {
                return;
            }
            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    url: "../annexfile/delete",
                    params: JSON.stringify(ids),
                    type: "POST",
                    contentType: "application/json",
                    successCallback: function () {
                        alert('操作成功', function (index) {
                            vm.annexListReload();
                        });
                    }
                });
            });
        },
        //显示备件列表-物料编码
        getSparePart: function () {
            let _this = this;
            if (vm.devKind == '1') {
                // 生产设备 sparePartmaintenanceDetails
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-file-text-o"></i> 选择备件',
                    // content: '../spare/sparePartQuery.html',
                    content: '../spare/sparePartmaintenanceDetails.html?materialType=2',
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var iframeWin = window["layui-layer-iframe" + index];
                        var res = iframeWin.getSparePart();
                        if (res.actualNum - res.replaceNum < 0) {
                            alert('可用数据小于1');
                            return
                        }
                        vm.sparePartConsumRecord = {
                            num: 0,
                            materialRecordId: res.id, // 领料明细ID
                            businessId: _this.businessId, // 维修记录ID
                            type:'REPAIR',
                        };
                        layer.close(index);
                        Ajax.request({
                            url: "../sparepartconsumrecord/save",
                            params: JSON.stringify(vm.sparePartConsumRecord),
                            type: "POST",
                            contentType: "application/json",
                            successCallback: function (r) {
                                alert('操作成功', function (index) {
                                    vm.reload();
                                });
                            }
                        });
                    }
                })
            } else if (vm.devKind == '2') {
                // 能源设备从备件库存中选择
                openWindow({
                    type: 2,
                    title: '<i class="fa fa-file-text-o"></i> 选择备件',
                    content: '../spare/sparestock_choose.html',
                    btn: ['确定', '取消'],
                    btn1: function (index) {
                        var iframeWin = window["layui-layer-iframe" + index];
                        var res = iframeWin.getSpareStroe();
                        if (!res) {
                            iview.Message.error("请选择一条记录");
                        } else {
                            let storeNum = parseInt(res.storeNum);
                            if (storeNum == 0 || (storeNum - parseInt(res.locNum) <= 0)) {
                                alert("可用库存不足，请更换!");
                                return;
                            }
                            vm.sparePartConsumRecord = {
                                num: 0,
                                sparePartId: res.spareId,
                                businessId: _this.businessId,
                                type: _this.type,
                                posId: res.id
                            };
                            layer.close(index);
                            Ajax.request({
                                url: "../sparepartconsumrecord/save",
                                params: JSON.stringify(vm.sparePartConsumRecord),
                                type: "POST",
                                contentType: "application/json",
                                successCallback: function (r) {
                                    alert('操作成功', function (index) {
                                        vm.reload();
                                    });
                                }
                            });
                        }
                    }
                })
            }
        },
        handleBeforeUpload: function(){
            this.$refs.uploadFile.clearFiles();
            this.$Loading.start();
        },
        handleSuccess: function (res, file) {
            if(res.code == 0){
                this.$Loading.finish();
                iview.Message.success('文件上传成功!');
                vm.annexFile.url = res.url;
                vm.annexFile.fileName = res.fileName;
                vm.annexFile.relName = res.name;
            }else{
                this.$Loading.error();
                iview.Message.error('文件上传失败!');
            }
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        /*
        * 添加
        * */
        repairMeasureAdd(){
            let dutyUserId = '';
            //处理人默认第一个为自己
            if(vm.dutyUserIdList.length>0){
                dutyUserId = vm.dutyUserIdList[0].value;
            }
          vm.devMaintenRepair.preventMeasureList.push({
              content:'',
              startDate:'',
              endDate:'',
              measureType:'DEV_MAINTENANCE_TICKET',
              dutyUserId:dutyUserId,
              isShow:''
          })
        },
        /*
        * 加入关键零部件
        * */
        joinTheKey(){

            var id = getSelectedRow("#swapRecord");
            if (id == null) {
                return;
            }
            var data = getSelectedRowData("#swapRecord")
            let urls = '../sparePartKey/loadCjKeySpList?devId='+vm.devMaintenRepair.devId+'&spareId='+data.sparePartId
            Ajax.request({
                url: urls,
                type: "GET",
                contentType: "application/json",
                successCallback: function (r) {
                    if(r.list.length>0){
                        vm.isSelect = true;
                        vm.isList = true;
                        vm.keyPartList = r.list;
                    }else {
                        vm.isSelect = false
                        vm.isList = false;
                    }
                    vm.keyModal = true;
                }
            });

        },
        /*关键零部件确定*/
        keyOk:function () {
            var data = getSelectedRowData("#swapRecord")
            vm.keyQuarms.sparePartConsumeRecordId = data.id
            Ajax.request({
                url: '../sparePartKey/addKeySparePart',
                type: "POST",
                params: JSON.stringify(vm.keyQuarms),
                contentType: "application/json",
                successCallback: function (r) {
                    vm.keyQuarms.position = ''
                    vm.reload();
                }
            });
        },
        /*取消关键零部件*/
        keyCancel:function (){
            console.log('点击了清除数')
        },
        // 清除关键零部件位置
        clearKey:function (){
          vm.isSelect = !vm.isSelect;
          vm.keyQuarms.position = ''
        },
        /*
        * 移除维修措施明细
        * */
        delRepairMeasureDetail(Index){
           vm.devMaintenRepair.preventMeasureList.splice(Index,1)
        },
        preview: function (url) {
            if (url) {
                window.open(url, '_blank');
            } else {
                alert('还未上传文件');
            }
        },
        /*
      * 1.报警代码切换
      * */
        showLoc: function (type) {
            // 清空报警代码相关的内容
            this.$set(this.devMaintenRepair, 'faultId', '');
            this.$set(this.devMaintenRepair, 'faultCode', '');
            this.$set(this.devMaintenRepair, 'faultDesc', '');
            // 切换报警代码：选择和手动录入显示
            vm.flag = 1 - type;
        },
        // 加载报警代码
        loadAlarmCategory(queryCondition, callback) {
            Ajax.request({
                url: '../alarmcategory/queryAll?' + queryCondition,
                async: true,
                successCallback: data => {
                    if (data.list == 0) {
                        alert('无可选设备报警分类，请等待维护完毕后再进行完善！')
                        return;
                    }
                    callback(data.list);
                }
            });
        },
        /*
        * 1.切换时清空小类 和小类数组
        * 2. 获取小类数组
        * */
        handleVfgChange(vfgOption) {
            // 设置CCCID
            this.devMaintenRepair.vfgId = vfgOption;
            // 清空
            vm.devMaintenRepair.faultCategoryId = '';
            vm.devMaintenRepair.faultCategoryName = '';
            vm.devMaintenRepair.faultId = '';
            vm.devMaintenRepair.faultCode = '';
            vm.devMaintenRepair.faultDesc = '';

            // 清空CCC列表
            this.cccList = [];
            // 清空设备报警代码列表
            this.alarmList = [];
            // 加载CCC列表
            vm.loadAlarmCategory('pid=' + vfgOption, function (dataList) {
                vm.cccList = dataList;
            });
        },
        /*
            报警小类切换时 1.会加载出来报警代码，自动回填
        */
        handleCccChange(cccOption) {
            // 设置CCCID
            this.devMaintenRepair.faultCategoryId = cccOption;
            // 清空报警代码库
            this.devMaintenRepair.faultId = '';
            this.devMaintenRepair.faultCode = '';
            this.devMaintenRepair.faultDesc = '';
            // 清空设备报警代码列表并重新加载
            this.alarmList = [];
            this.loadDevAlarmList(cccOption, vm.devMaintenRepair.devId);
        },
        // 加载设备备件代码列表
        loadDevAlarmList(cccId, devId) {
            Ajax.request({
                url: '../alarmcodebase/queryAll?alarmCategoryId=' + cccId + '&devId=' + devId,
                async: true,
                successCallback: data => {
                    this.alarmList = data.list;
                }
            });
        },
        // 加载维修记录详情
        loadRepairRecordDetail(ticketId) {
            const that = this;
            Ajax.request({
                url: "../devRepairRecord/info/" + ticketId,
                async: false,
                successCallback: function (r) {
                    if (r.devMaintenRepair) {
                        vm.devMaintenRepair.devId = r.devMaintenRepair.devId;
                        vm.devMaintenRepair.devName = r.devMaintenRepair.devName;
                        vm.devMaintenRepair.devCode = r.devMaintenRepair.devCode;
                        vm.devMaintenRepair.faultCode = r.devMaintenRepair.faultCode;
                        vm.devMaintenRepair.faultId = r.devMaintenRepair.faultId;
                        vm.devMaintenRepair.faultDesc = r.devMaintenRepair.faultDesc;
                        vm.devMaintenRepair.vrtId = r.devMaintenRepair.vrtId;
                        vm.devMaintenRepair.vfgId = r.devMaintenRepair.vfgId;
                        vm.devMaintenRepair.faultCategoryId = r.devMaintenRepair.faultCategoryId;
                        vm.devMaintenRepair.faultCategoryName = r.devMaintenRepair.faultCategoryName;
                        vm.devMaintenRepair.vrtName = r.devMaintenRepair.vrtName;
                        vm.devMaintenRepair.recordDescr = r.devMaintenRepair.recordDescr;
                        vm.devMaintenRepair.reason = r.devMaintenRepair.reason;
                        vm.devMaintenRepair.solution = r.devMaintenRepair.solution;
                        vm.devMaintenRepair.remark = r.devMaintenRepair.remark;
                        vm.devMaintenRepair.id = r.devMaintenRepair.id;
                        vm.devMaintenRepair.repairStartDate = r.devMaintenRepair.repairStartDate;
                        vm.devMaintenRepair.repairEndDate = r.devMaintenRepair.repairEndDate;
                        vm.devMaintenRepair.devTypeS = r.devMaintenRepair.devTypeS;
                        vm.devMaintenRepair.preventMeasureList = r.devMaintenRepair.preventMeasureList;
                        vm.devMaintenRepair.attachment = r.devMaintenRepair.attachment;
                        vm.devMaintenRepair.faultImages = r.devMaintenRepair.faultImages;
                        vm.desc = JSON.parse(JSON.stringify(r.devMaintenRepair.faultCode+r.devMaintenRepair.faultDesc));
                        vm.businessId =  r.devMaintenRepair.originRepairRecordId;
                        vm.keyQuarms.repairRecordId =  r.devMaintenRepair.originRepairRecordId;
                        vm.source =  r.devMaintenRepair.source;
                        vm.devCodeAndName = JSON.parse(JSON.stringify(r.devMaintenRepair.devCode+' '+r.devMaintenRepair.devName))
                        //如果报警代码存在flag ==0
                        if(r.devMaintenRepair.faultId){
                            vm.flag = '0'
                        }
                        // 如果故障分类ID存在，那么加载报警列表
                        if (r.devMaintenRepair.faultCategoryId) {
                            vm.loadDevAlarmList(r.devMaintenRepair.faultCategoryId, r.devMaintenRepair.devId)
                        }
                        // 如果小类存在存在，那么加载报警列表
                        if (r.devMaintenRepair.vrtId) {
                            vm.loadAlarmCategory('pid=' + r.devMaintenRepair.vrtId, function (vfgList) {
                                vm.vfgList = vfgList;
                                if (r.devMaintenRepair.vfgId) {
                                    vm.loadAlarmCategory('pid=' + r.devMaintenRepair.vfgId, function (cccList) {
                                        vm.cccList = cccList;
                                    });
                                }
                            });
                        }
                        /*加载换件记录*/
                        that.getChangeRecord()
                        /*加载附件列表*/
                        that.getAnnexList()
                    }
                }
            });
        }
    }
});

getDateform = function () {
    return vm.devMaintenRepair;
}
